package 复习.面试TOP101.链表;

import java.util.Stack;

public class 链表中的节点每K个一组翻转 {
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        Stack<ListNode> stack = new Stack<>();
        ListNode node = new ListNode(-1);
        ListNode temp = node;
        while(true){
            for(int i = 0;i < k && head != null;i++){
                stack.add(head);
                head = head.next;
            }
            if(stack.size() < k){
                break;
            }else{
                while(!stack.isEmpty()){
                    temp.next = stack.pop();
                    temp = temp.next;
                    temp.next = null;
                }
            }
        }
        ListNode cur = null;
        while(!stack.isEmpty()){
            cur = stack.pop();
        }
        temp.next = cur;
        return node.next;
    }
}
